package com.pearadmin.pro.modules.oss.cloud.impl;

import cn.hutool.extra.ftp.Ftp;
import com.pearadmin.pro.common.web.exception.base.BusinessException;
import com.pearadmin.pro.modules.oss.cloud.StorageService;
import com.pearadmin.pro.modules.oss.domain.SysOss;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDate;
import java.util.UUID;

@Component
public class FTPStorageService implements StorageService {
    @Resource
    private FTPStorageConfig config;

    @Resource
    private Ftp ftp;

    @Override
    public String upload(MultipartFile file) {
//        Ftp ftp = new Ftp(config.getHost(), config.getPort(), config.getUser(), config.getPassword());
        String original = file.getOriginalFilename();
        String suffix = original.substring(original.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString();
        String newName = fileName + suffix;
        LocalDate currentDate = LocalDate.now();
        String path = config.getRootPath() + '/' + currentDate.getYear() + '/' + currentDate.getMonthValue() + '/' + currentDate.getDayOfMonth();
        try {
            ftp.init();
            if (!ftp.exist(path)) {
                ftp.mkDirs(path);
            }
            ftp.upload(path, newName, file.getInputStream());
            ftp.close();
        } catch (IOException e) {
            throw new BusinessException(e.getMessage());
        }
        return path + '/' + newName;
    }

    /**
     * 将文件写入输出流
     *
     * @param sysOss
     * @param outputStream
     */
    public void download(SysOss sysOss, OutputStream outputStream) {
        String path = sysOss.getPath();
        try {
            ftp.init();
            ftp.download(path.substring(0, path.lastIndexOf('/')), path.substring(path.lastIndexOf('/') + 1), outputStream);
            ftp.close();
        } catch (IOException e) {
            throw new BusinessException(e.getMessage());
        }

    }
}
